package grpc_demo

import (
	"net"
	"protobuf/pb"

	"github.com/hashicorp/consul/api"
	"github.com/sirupsen/logrus"
	"google.golang.org/grpc"
)

func RunServer() error { // 初始化consul配置，客户端服务器需要一致
	// 获取consul操作对象
	client, err := api.NewClient(&api.Config{
		Address: "172.19.129.62:8500",
	})
	if err != nil {
		logrus.Fatal(err)
	}

	// 注册服务，服务的常规配置
	registerService := api.AgentServiceRegistration{
		ID:      "1",
		Name:    "FutureService",
		Tags:    []string{"grpc", "consul"},
		Port:    1234,
		Address: "127.0.0.1",
		Check: &api.AgentServiceCheck{
			CheckID:  "consul grpc test",
			TCP:      "127.0.0.1:1234",
			Timeout:  "5s",
			Interval: "5s",
		},
	}

	// 将服务注册到consul上
	err = client.Agent().ServiceRegister(&registerService)
	if err != nil {
		return err
	}

	// 设置监听
	listener, err := net.Listen("tcp", ":1234")
	if err != nil {
		return err
	}

	// 构造gRPC对象
	grpcServer := grpc.NewServer()
	// 注册服务
	pb.RegisterFutureServer(grpcServer, &FutureGrpcServer{})

	// 启动服务
	err = grpcServer.Serve(listener)
	return err
}
